package com.toe.commodity.webapi.service.impl;

import com.toe.commodity.service.CommodityPictureService;
import com.toe.commodity.webapi.constant.Constants;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.io.IOException;

import static com.toe.commodity.webapi.constant.Constants.PICTURE_PATH;

@Service
@DubboService
public class CommodityPictureServiceImpl implements CommodityPictureService {
    //图片上传功能

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
        factory.setMaxFileSize(DataSize.of(20, DataUnit.MEGABYTES));
        // 设置总上传数据总大小10M
        factory.setMaxRequestSize(DataSize.of(20, DataUnit.MEGABYTES));
        return factory.createMultipartConfig();
    }

    @Configuration
    public static class MyPicConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/commodityPicture/**")
                    .addResourceLocations(Constants.PICTURE_PATH);
        }
    }

    // 上传图片
    @Override
    public String pictureUpload(MultipartFile urlFile) {

        String fileName = System.currentTimeMillis() + urlFile.getOriginalFilename();
        String filePath = PICTURE_PATH + System.getProperty("file.separator") + "img";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/img/" + fileName;
        if (!dest.exists()) {
            try {
                urlFile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return storeUrlPath;
    }
}

